package gspushmq.util;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;

import gogoal.api.GoGoalAPI;
import gspushmq.model.GsConfig;

public enum TokenMQ {

	tokenMQ,
	detailDate;
	
	private String token;
	private Date preDate = getNowDate();
	private Date preDetailDate = getNowDate();

	private TokenMQ() {
		reload();
	}

	/**
	 * 调接口，获取token，并设置
	 * 
	 * @author yutao
	 * @date 2018年1月11日上午10:27:46
	 */
	private void reload() {
		token = null;
		try {
			Map<String, String> params = new HashMap<String, String>();
			String tokenValue = "{\"AccountId\":" + 1 + ",\"UserId\":" + 1 + ",\"LoginId\":" + 1 + ",\"Name\":\"" +"GMEMQ"+ "\"}";
			params.put("value", tokenValue);
			params.put("time", String.valueOf(60*60*24));
			String apiUrlStr = "v1/system/add_token";
			String resultStr = GoGoalAPI.get(GsConfig.config.getDomain(), GsConfig.config.getAppKey(), GsConfig.config.getAppSecret(), apiUrlStr, params);
			
			JSONObject jsonResult = (JSONObject) JSONObject.parse(resultStr);
			Integer code = jsonResult.getInteger("code");
			if(code == 0){
				JSONObject result = jsonResult.getJSONObject("data");
				token = result.getString("result");
				//时间置为最新的时间
				preDate = getNowDate();
				GGLogger.warn(TokenMQ.class, "----reload----获取到的token----" + token);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public String getToken() {
		//如果过了一天，或者token为null，就重新获取token
		if(getNowDate().getTime() > preDate.getTime() || token == null){
			reload();
		}
		return token;
	}
	
	/**
	 * 重新获取token
	 * @return
	 * @author yutao
	 * @date 2018年1月12日下午5:01:47
	 */
	public String getReLoadToken(){
		reload();
		return token;
	}

	public void setToken(String token) {
		this.token = token;
	}
	
	/**
	 * 获取当前时间，去掉时分秒
	 * @return
	 * @author yutao
	 * @date 2018年1月11日上午10:35:45
	 */
	public static Date getNowDate(){
		Calendar cal = Calendar.getInstance();
		cal.set(Calendar.MILLISECOND, 000);
		cal.set(Calendar.SECOND, 0);
		cal.set(Calendar.MINUTE, 0);
		cal.set(Calendar.HOUR_OF_DAY, 0);
		return cal.getTime();
	}

	public Date getPreDetailDate() {
		return preDetailDate;
	}

	public void setPreDetailDate(Date preDetailDate) {
		this.preDetailDate = preDetailDate;
	}
}
